<template>
  <div class="chooseTeacher">
    <el-button size="mini" type="primary" @click="show = true"
      >打开指导学生列表</el-button
    >
    <el-dialog
      :title="`您指导的学生（${tableData.filter(i => !i.isRemove).length}人）`"
      :visible="show"
      :before-close="handleClose"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-table :data="tableData" style="width: 100%" row-key="chooseNo">
        <el-table-column label="姓名" width="100">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>姓名: {{ scope.row.realName }}</p>
              <div slot="reference" class="name-wrapper">
                {{ scope.row.realName }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="选报时间" width="180">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>选报时间: {{ gRenderTime(scope.row.chooseTime) }}</p>
              <div slot="reference" class="name-wrapper">
                {{ gRenderTime(scope.row.chooseTime) }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="学号">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>学号: {{ scope.row.stuNum }}</p>
              <div slot="reference" class="name-wrapper">
                {{ scope.row.stuNum }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="danger"
              @click="update(scope.$index, scope.row)"
              >修改</el-button
            > -->
            <el-button
              v-if="!scope.row.isRemove"
              size="mini"
              type="danger"
              @click="confirmDelete(scope.$index, scope.row)"
              >移除</el-button
            >
            <el-button
              v-else
              size="mini"
              type="success"
              @click="
                handleUpdateTutor(
                  scope.$index,
                  scope.row,
                  userInfo.userID,
                  true
                )
              "
              >恢复</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-button
          style="margin-top: 10px; margin-left: auto; display: block"
          size="mini"
          type="primary"
          v-if="tableData.length"
          @click.stop.passive="confirmList"
          >确认</el-button
        >
        <el-button
          style="margin-top: 10px; margin-left: auto; display: block"
          size="mini"
          type="primary"
          v-else
          @click="show = false"
          >关闭</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :title="`修改学生（${filterName(stuInfo)}）指导教师`"
      :visible="showUpdate"
      :before-close="handleCloseUpdate"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-radio-group v-model="checkTeacher">
        <div
          class="teacherBox"
          v-for="(Titem, Tindex) in filterTeacher"
          :key="Tindex"
          :class="{ isSelectTeacher: checkTeacher == Titem.userID }"
        >
          <el-radio :label="Titem.userID" style="min-width: 480px">{{
            filterName(Titem) + `  -  已选人数（${Titem.selectedStuCount}）`
          }}</el-radio>
        </div>
      </el-radio-group>
      <div v-if="!filterTeacher.length" style="margin-bottom: 10px">
        无可选教师
      </div>
      <el-button
        size="mini"
        type="primary"
        @click="confirmUpdate"
        :disabled="!checkTeacher"
        >确认</el-button
      >
    </el-dialog>
  </div>
</template>

<script>
import { getChooseUpdateTutor } from "@/request/courses";
import { renderTime } from "@/util/tool";
import { mapState } from "vuex";
import { Session } from "@/util/storage/session"
export default {
  data() {
    return {
      show: false,
      showUpdate: false,
      popVisible: false,
      tableData: [],
      filterUser: [],
      filterUserSave: [],
      stuInfo: {},
      checkTeacher: null,
    };
  },
  props: {
    courseInfo: Object,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      getChooseCourses: function (state) {
        return state.courses.chooseCourses;
      },
    }),
    filterTeacher() {
      let arr = [];
      this.courseInfo.tutorMapJson.filter((item) => {
        let t = this.courseInfo?.tutorList?.find(
          (f) => f.userID == item.tutorID
        );
        if (!item.classIDs.length) arr.push();
        if (item.classIDs.includes(this.stuInfo.classID)) {
          return t && arr.push(t);
        }
        if (this.stuInfo.otherClassIDList) {
          this.stuInfo.otherClassIDList
            .split(",")
            .map((i) => Number(i))
            .forEach((oitem) => {
              if (item.classIDs.includes(oitem)) {
                t && arr.push(t);
              }
            });
        }
      });
      return arr;
    },
    filterName() {
      return function (data) {
        return data.realName || data.nickName || data.email || data.regName;
      };
    },
    filterIconPath() {
      return function (data) {
        return data.iconPath || "";
      };
    },
    gRenderTime() {
      return function (time) {
        return renderTime(time);
      };
    },
  },
  watch: {
    courseInfo(n) {
      this.getStu();
    },
    show() {
      this.getStu();
    },
  },
  created() {
    this.getStu();
  },
  methods: {
    handleClose() {
      this.show = false;
    },
    handleCloseUpdate() {
      this.showUpdate = false;
      this.checkTeacher = null;
    },
    closeVisible() {
      this.visible = false;
    },
    getStu() {
      let fUser = this.courseInfo?.tutorList?.find(
        (item) => item.userID == this.userInfo.userID
      );
      if (fUser) {
        this.tableData =
          fUser.stuChooses?.filter(
            (item) => !this.filterUser.includes(item.userID)
          ) || [];
      } else this.tableData = [];
    },
    handleUpdateTutor(i, row, id, isEqual) {
      const params = {
        tutorID: id || 0,
        chooseNo: Number(row.chooseNo),
      };
      getChooseUpdateTutor(params).then((res) => {
        if (res.errno == 0) {
          this.$antdMessage.success({
            content: id ? "修改成功" : "移除成功",
          });
          this.$set(row, "isRemove", true);
          localStorage.removeItem("courseInfo");
          this.filterUserSave.push(row.userID);
          Session.remove(`/api/choose/mylist?userID=${this.userInfo.userID}`)
          // if (isEqual !== undefined) this.showUpdate = false;
          if (id) {
            this.filterUserSave = this.filterUserSave.filter(
              (i) => i !== row.userID
            );
            row.isRemove = false;
          }
          this.getStu();
        } else {
          {
            this.$antdMessage.error({
              content: res.message,
            });
          }
        }
      });
    },
    confirmDelete(i, r) {
      this.$confirm("是否确认移除学生", {
        title: "提示",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        callback: (action) => {
          if (action == "confirm") this.handleUpdateTutor(i, r, 0);
        },
      });
    },
    confirmUpdate() {
      this.handleUpdateTutor(
        null,
        this.stuInfo,
        this.checkTeacher,
        this.stuInfo.tutorID == this.checkTeacher
      );
    },
    update(i, r) {
      this.stuInfo = r;
      this.showUpdate = true;
    },
    confirmList() {
      if (this.filterUserSave.length) {
        this.$confirm("是否确认修改的名单", {
          title: "提示",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "success",
          callback: (action) => {
            if (action == "confirm") {
              this.save();
              this.$parent.handleCourseDetailCreate();
            }
          },
        });
      } else {
        this.save();
      }
    },
    save() {
      this.filterUser = JSON.parse(JSON.stringify(this.filterUserSave));
      this.show = false;
      this.filterUserSave = [];
    },
  },
};
</script>

<style lang="stylus">
.chooseTeacher {
}

.isOldSeleceTeacher {
  .el-radio__label {
    background: #000;
  }
}
</style>